﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Volo.Abp;

using Wms.Manager.Wms.InventoryManagements;
using Wms.Manager.Wms.InventoryManagements.Dtos;

namespace Wms.Manager.Controllers
{
    [Area("app")]
    [Route("api/app/inventory-management")]
    public class InventoryManagementController:ManagerController
    {
        private readonly IInventoryManagementAppService _appService;

        public InventoryManagementController(IInventoryManagementAppService appService)
        {
            _appService = appService;
        }

        [HttpPost("export")]
        public async Task<IActionResult> ExportAsync(ExportRequest request)
        {
            var fileBytes = await _appService.ExportInventoryAsync(request.Ids);
            var fileName = $"库存管理数据_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }

        [HttpGet("export-template")]
        public async Task<IActionResult> ExportTemplateAsync()
        {
            var fileBytes = await _appService.ExportTemplateAsync();
            var fileName = $"库存管理导入模板_{DateTime.Now:yyyyMMddHHmmss}.xlsx";

            return File(fileBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
        }

        [HttpPost("import")]
        public async Task<InventoryManagementImportResult> ImportAsync(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                throw new UserFriendlyException("请选择要导入的文件");
            }

            if (!IsExcelFile(file))
            {
                throw new UserFriendlyException("文件格式不正确，请上传Excel文件(.xlsx或.xls)");
            }

            using var stream = file.OpenReadStream();
            var importResult = await _appService.ImportInventoryAsync(stream);

            var result = new InventoryManagementImportResult
            {
                TotalRows = importResult.TotalRows,
                SuccessCount = importResult.SuccessCount,
                ErrorCount = importResult.ErrorCount,
                Errors = importResult.Errors
            };

            if (importResult.HasErrors)
            {
                result.Success = false;
                result.Message = $"导入完成，成功 {importResult.SuccessCount} 条，失败 {importResult.ErrorCount} 条";
            }
            else
            {
                // 保存成功的数据
                 await _appService.InsertManyAsync(importResult.SuccessData);
                result.Success = true;
                result.Message = $"成功导入 {importResult.SuccessCount} 条数据";
            }
            return result;
        }
        private static bool IsExcelFile(IFormFile file)
        {
            var allowedExtensions = new[] { ".xlsx", ".xls" };
            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            return allowedExtensions.Contains(extension);
        }
    }
}
